﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using System.Xml;
using Altairis.FluffyCloud.Data;
using Altairis.Web;

namespace Altairis.FluffyCloud.WebCore.Handlers {

    public class MessagesFeedHandler : IHttpHandler {

        public bool IsReusable {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context) {
            using (var dc = new FluffyDbContext()) {
                // Get user from security code
                var securityCode = context.Request.RequestContext.RouteData.Values["securityCode"] as string;
                var otherUserName = context.Request.RequestContext.RouteData.Values["userName"] as string;
                var user = dc.Users.SingleOrDefault(x => x.SecurityCode.Equals(securityCode, StringComparison.Ordinal));
                if (user == null) {
                    // User not found (security code invalid)
                    context.Response.SendErrorResponse(404, "Object Not Found", "Invalid security code");
                    return;
                }

                // Get messages
                var baseUrl = context.Request.ApplicationBaseUri().ToString() + "my/messages";
                var userName = user.UserName;
                var q = from m in dc.Messages
                        orderby m.DateCreated descending
                        where m.FromUserName.Equals(userName, StringComparison.CurrentCultureIgnoreCase) || m.ToUserName.Equals(userName, StringComparison.CurrentCultureIgnoreCase)
                        select m;

                if (!string.IsNullOrWhiteSpace(otherUserName)) {
                    // Filter also by second user name
                    q = q.Where(m => m.FromUserName.Equals(otherUserName, StringComparison.CurrentCultureIgnoreCase) || m.ToUserName.Equals(otherUserName, StringComparison.CurrentCultureIgnoreCase));
                }

                var items = new List<SyndicationItem>();
                foreach (var m in q) {
                    var item = new SyndicationItem {
                        Content = new TextSyndicationContent(m.Text, TextSyndicationContentKind.Plaintext),
                        PublishDate = m.DateCreated,
                    };
                    item.AddPermalink(new Uri(string.Format("{0}#{1:N}", baseUrl, m.MessageId)));
                    if (m.FromUserName.Equals(userName, StringComparison.OrdinalIgnoreCase)) {
                        // Sent message
                        item.Title = new TextSyndicationContent("Zpráva pro uživatele " + m.ToUserName.ToUpper(), TextSyndicationContentKind.Plaintext);
                    }
                    else {
                        // Received message
                        item.Title = new TextSyndicationContent("Zpráva od uživatele " + m.FromUserName.ToUpper(), TextSyndicationContentKind.Plaintext);
                    }
                    items.Add(item);
                }

                // Create feed header
                var feed = new SyndicationFeed("FluffyCloud: Zprávy uživatele " + userName.ToUpper(), "Přijaté a odeslané soukromé zprávy", new Uri(baseUrl), items) {
                    Generator = string.Format("FluffyCloud (www.fluffycloud.cz), {0}", Global.VersionString),
                    Items = items
                };

                if (!string.IsNullOrWhiteSpace(otherUserName)) {
                    feed.Title = new TextSyndicationContent(string.Format("FloffyCloud: Konverzace uživatele {0} s uživatelem {1}", userName.ToUpper(), otherUserName.ToUpper()));
                }

                // Save as RSS feed
                context.Response.ContentType = "text/xml";
                using (var xw = XmlWriter.Create(context.Response.Output)) {
                    feed.SaveAsRss20(xw);
                }
            }
        }
    }
}